package com.sasu.university_data.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class UpdateImage {
    public String handleFileUpload(MultipartFile file, String uploadDir) {
        if (file.isEmpty()) {
            return "上传失败，请选择一个文件";
        }

        try {
            // 确保上传目录存在
            File directory = new ClassPathResource(uploadDir).getFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 保存文件到本地目录
            byte[] bytes = file.getBytes();
            Path path = Paths.get(directory.getAbsolutePath() + File.separator + file.getOriginalFilename());
            Path classPathPath = Paths.get("D:\\IDEA\\IDEA workspace\\CollegeThird\\visualization_after\\src\\main\\resources" + File.separator + uploadDir + File.separator + file.getOriginalFilename());
            Files.write(path, bytes);
            Files.write(classPathPath, bytes);

            return "文件上传成功:" + file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "文件上传失败";
    }
}
